<template>
  <view class="public-page">
    <!-- 顶部导航 -->
    <Navbar title="公共区域管理" />

    <!-- 主要内容 -->
    <view class="content">
      <!-- 标题和图例 -->
      <view class="header-section">
        <text class="page-title">已选公共区域</text>
        <view class="legend-section">
          <view class="legend-item">
            <view class="legend-dot normal"></view>
            <text class="legend-text">正常</text>
          </view>
          <view class="legend-item">
            <view class="legend-dot abnormal"></view>
            <text class="legend-text">异常</text>
          </view>
        </view>
      </view>

      <!-- 表格区域 -->
      <view class="table-section">
        <!-- 筛选器表头 -->
        <view class="table-header">
          <areaFilterVue
            ref="areaFilterRef"
            :filterConfig="filterConfig"
            :areaData="filterAreaData"
            @filterChange="handleFilterChange"
          ></areaFilterVue>
        </view>

        <!-- Swiper区域 -->
        <view class="table-body">
          <tn-swiper
            v-model="currentSwiperIndex"
            :data="allTableData"
            :height="swiperHeight + 'rpx'"
            :indicator="false"
            :autoplay="false"
            :loop="false"
            @change="handleSwiperChange"
          >
            <template #default="{ data: tableData, index: tableIndex }">
              <!-- 表格容器 -->
              <view class="table-container">
                <!-- 表格内容 -->
                <scroll-view
                  class="table-content"
                  scroll-y="true"
                  :scroll-top="tableScrollTop"
                  show-scrollbar="false"
                >
                  <view
                    v-for="(item, index) in getDisplayData(tableData.data)"
                    :key="index"
                    class="row-item"
                  >
                    <view class="label-container">
                      <scroll-view
                        class="label-scroll"
                        scroll-x="true"
                        show-scrollbar="false"
                      >
                        <text class="label-text">{{ item.label }}</text>
                      </scroll-view>
                    </view>
                    <view class="scroll-container">
                      <scroll-view
                        class="horizontal-scroll"
                        scroll-x="true"
                        show-scrollbar="false"
                        @scroll="handleInnerScroll"
                      >
                        <view class="horizontal-scroll-inner">
                          <view
                            v-for="(subItem, subIndex) in item.data"
                            :key="subIndex"
                            class="data-item"
                            :class="{
                              normal: subItem.value === 'true',
                              abnormal: subItem.value === 'false',
                            }"
                          >
                            <view
                              class="legend-dot"
                              :class="
                                subItem.value === 'true' ? 'normal' : 'abnormal'
                              "
                            ></view>
                            <view class="data-text">{{
                              subItem.number || '-'
                            }}</view>
                          </view>
                        </view>
                      </scroll-view>
                    </view>
                  </view>
                </scroll-view>
              </view>
            </template>
          </tn-swiper>

          <!-- 自定义指示器 -->
          <view class="custom-indicator">
            <view
              v-for="(item, idx) in allTableData"
              :key="idx"
              class="indicator-dot"
              :class="{ active: idx === currentSwiperIndex }"
              @click="switchToIndex(idx)"
            ></view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部添加按钮 -->
    <view class="bottom-actions">
      <view class="add-btn" @click="handleAdd">添加</view>
    </view>

    <!-- 区域选择器 -->
    <tn-picker
      v-model:open="showAreaPicker"
      :data="areaPickerData"
      :model-value="areaValue"
      :immediate-change="false"
      :mask="true"
      :show-cancel="false"
      confirm-color="#1ec8e1"
      label-key="label"
      value-key="value"
      @confirm="onAreaConfirm"
    />
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import Navbar from '@/components/Navbar.vue';
import areaFilterVue from '@/components/areaFilter.vue';
import { createRequest } from '@/utils/request';

// 筛选器相关
const areaFilterRef = ref(null);
const filterConfig = ref({
  labels: ['区域', '子区域'],
});

// 筛选数据 - 页面独立请求
const filterAreaData = ref([]);
const filterDataLoaded = ref(false);

// Swiper相关
const currentSwiperIndex = ref(0);
const swiperHeight = ref(0);
const tableScrollTop = ref(0);

// 表格数据
const allTableData = ref([]);

// 区域选择器相关
const showAreaPicker = ref(false);
const areaValue = ref([]);
const areaLabel = ref('');
const areaPickerData = ref([]);

// 获取筛选区域数据
const fetchFilterAreaData = async () => {
  try {
    // 调用真实的API请求
    const response = await createRequest(`/region/getRemainingHierarchyInPublicArea`, {
      method: 'get',
    });

    // 验证响应数据
    if (response && response.code === 200 && response.data && Array.isArray(response.data)) {
      // 转换数据格式，只保存有用的信息
      filterAreaData.value = response.data.map(item => ({
        value: item.id,
        label: item.regionName,
        children: item.child ? item.child.map(child => ({
          value: child.id,
          label: child.regionName,
          children: [] // 筛选器只显示两级，第三级数据通过接口获取
        })) : []
      }));
    } else {
      console.warn('接口返回数据格式异常:', response);
      filterAreaData.value = [];
    }

    filterDataLoaded.value = true;
  } catch (error) {
    console.error('获取筛选区域数据失败:', error);
    filterAreaData.value = [];
    filterDataLoaded.value = false;
  }
};

// 获取区域选择器数据
const fetchAreaPickerData = async () => {
  try {
    // 调用真实的API请求
    const response = await createRequest(`/region/getRemainingHierarchyInPublicArea`, {
      method: 'get',
    });

    // 验证响应数据
    if (response && response.code === 200 && response.data && Array.isArray(response.data)) {
      // 转换数据格式，只保存有用的信息
      areaPickerData.value = response.data.map(item => ({
        label: item.regionName,
        value: item.id,
        children: item.child ? item.child.map(child => ({
          label: child.regionName,
          value: child.id,
          children: child.child ? child.child.map(grandChild => ({
            label: grandChild.regionName,
            value: grandChild.id,
            children: grandChild.devices ? grandChild.devices.map(device => ({
              label: device.deviceName,
              value: device.deviceId
            })) : []
          })) : []
        })) : []
      }));
    } else {
      console.warn('接口返回数据格式异常:', response);
      areaPickerData.value = [];
    }
  } catch (error) {
    console.error('获取区域选择器数据失败:', error);
    areaPickerData.value = [];
  }
};

// 区域选择器确认事件
const onAreaConfirm = async (val, item) => {
  // val 是选中的 value 数组,item 是选中的对象数组
  areaValue.value = val;
  // 格式化显示文本
  areaLabel.value = formatAreaDisplay(item);
  showAreaPicker.value = false;

  console.log('选择的区域:', areaLabel.value, '区域值:', areaValue.value);

  try {
    // 提取楼层ID（第三级）和设备ID（第四级）
    const thirdLevelRegionId = val[2]; // 楼层ID
    const monitorDeviceId = val[3];     // 设备ID

    console.log('准备添加设备:', { thirdLevelRegionId, monitorDeviceId });

    // 调用添加设备接口
    const response = await createRequest(`/public-area/report`, {
      method: 'post',
      data: {
        thirdLevelRegionId: thirdLevelRegionId,
        monitorDeviceId: monitorDeviceId
      }
    });

    if (response && response.code === 200) {
      console.log('设备添加成功:', response);
      // 返回上一页面
      uni.navigateBack();
    } else {
      console.error('设备添加失败:', response);
    }
  } catch (error) {
    console.error('添加设备请求失败:', error);
  }
};



// 格式化区域显示文本
const formatAreaDisplay = item => {
  if (!item || !Array.isArray(item)) {
    return '选择区域';
  }

  // 提取标签文本
  const labels = item.map(i => i.label).filter(Boolean);
  return labels.length > 0 ? labels.join(' - ') : '选择区域';
};

// 处理筛选器变化
const handleFilterChange = async filterData => {
  console.log('筛选变化:', filterData);

  // 获取当前筛选层级数据
  const currentLevels = areaFilterRef.value?.filterLevels || [];

  // 检查是否有有效的筛选数据
  if (currentLevels.length === 0) {
    console.log('没有筛选层级数据');
    return;
  }

  // 获取最后一级筛选
  const lastLevel = currentLevels[currentLevels.length - 1];
  if (!lastLevel || lastLevel.options.length === 0) {
    console.log('最后一级筛选没有选项');
    allTableData.value = [];
    currentSwiperIndex.value = 0;
    updateSwiperHeight();
    return;
  }

  // 检查是否选择了"全部"
  const selectedOption = lastLevel.options[lastLevel.selectedIndex];
  if (selectedOption && selectedOption.value === 'all') {
    console.log('选择了全部，清空数据');
    allTableData.value = [];
    currentSwiperIndex.value = 0;
    updateSwiperHeight();
    return;
  }

  // 动态判断筛选类型和层级
  const currentLevelIndex = parseInt(filterData.type.replace('filter', '')) - 1;
  const isLastLevel = currentLevelIndex === currentLevels.length - 1;

  if (isLastLevel) {
    // 最后一级筛选变化：同步swiper索引
    const targetIndex = filterData.targetIndex;
    if (
      targetIndex !== undefined &&
      targetIndex >= 0 &&
      targetIndex < allTableData.value.length
    ) {
      console.log('同步swiper索引到:', targetIndex);
      currentSwiperIndex.value = targetIndex;
      updateSwiperHeight();
    }
  } else {
    // 非最后一级筛选变化：重新获取数据
    console.log('重新获取数据');
    await fetchTableData(filterData);
    currentSwiperIndex.value = 0;
    updateSwiperHeight();
  }
};

// 获取表格数据
const fetchTableData = async (filterData = null) => {
  try {
    // 获取当前筛选层级数据
    const currentLevels = areaFilterRef.value?.filterLevels || [];
    const lastLevel = currentLevels[currentLevels.length - 1];

    if (!lastLevel || lastLevel.options.length === 0) {
      allTableData.value = [];
      return;
    }

    // 为每个最后一级筛选的选项获取数据
    const promises = lastLevel.options.map(async option => {
      try {
        // 调用真实的API请求获取设备状态数据
        const response = await createRequest(`/public-area/status/list/${option.value}`, {
          method: 'get',
          showLoading: false
        });

        // 验证响应数据
        if (response && response.code === 200 && response.data && Array.isArray(response.data)) {
          // 转换数据格式，将接口返回的数据转换为表格需要的格式
          const tableData = response.data.map(item => ({
            label: item.regionName,
            data: item.devices ? item.devices.map(device => ({
              id: device.deviceId,
              number: device.deviceName,
              value: device.runStatus === 1 ? 'true' : 'false' // 1表示正常，其他表示异常
            })) : []
          }));

          return {
            title: option.label,
            data: tableData,
          };
        } else {
          console.warn(`区域 ${option.label} 返回数据格式异常:`, response);
          return {
            title: option.label,
            data: [],
          };
        }


      } catch (error) {
        console.error(`获取区域 ${option.label} 数据失败:`, error);
        return {
          title: option.label,
          data: [],
        };
      }
    });

    const tableData = await Promise.all(promises);
    allTableData.value = tableData;
  } catch (error) {
    console.error('获取表格数据失败:', error);
    allTableData.value = [];
  }
};



// swiper 变化事件处理
const handleSwiperChange = index => {
  // 获取当前筛选层级数据
  const currentLevels = areaFilterRef.value?.filterLevels || [];

  // 如果有筛选层级，同步更新最后一级筛选组件
  if (currentLevels.length > 0) {
    const lastLevelIndex = currentLevels.length - 1;
    const lastLevel = currentLevels[lastLevelIndex];
    if (lastLevel && index < lastLevel.options.length) {
      // 使用新的筛选组件API更新最后一级索引
      areaFilterRef.value?.updateLevelIndex(lastLevelIndex, index);
    }
  }
  updateSwiperHeight();
};

// 切换到指定索引
const switchToIndex = index => {
  if (index === currentSwiperIndex.value) return;
  currentSwiperIndex.value = index;
  updateSwiperHeight();

  // 获取当前筛选层级数据
  const currentLevels = areaFilterRef.value?.filterLevels || [];

  // 如果有最后一级筛选，同步更新筛选组件
  if (currentLevels.length > 0) {
    const lastLevel = currentLevels[currentLevels.length - 1];
    if (lastLevel && index < lastLevel.options.length) {
      // 使用新的筛选组件API更新最后一级索引
      areaFilterRef.value?.updateLevelIndex(currentLevels.length - 1, index);
    }
  }
};

// 更新 swiper 高度
const updateSwiperHeight = () => {
  nextTick(() => {
    if (allTableData.value.length === 0) {
      swiperHeight.value = 0;
      return;
    }
    const currentTableData = allTableData.value[currentSwiperIndex.value];
    if (currentTableData && Array.isArray(currentTableData.data)) {
      const rowCount = currentTableData.data.length;
      const visibleRows = Math.min(rowCount, 12);
      const rowHeight = 60 + 16 + 16; // .row-item: min-height + padding-top + padding-bottom
      const borderPerRow = 1; // border-bottom: 1rpx
      const estimatedHeight =
        visibleRows > 0
          ? visibleRows * rowHeight + (visibleRows - 1) * borderPerRow
          : 0;
      swiperHeight.value = estimatedHeight;
    }
  });
};

// 获取显示数据
const getDisplayData = data => (data || []).slice();

// 处理内部滚动
const handleInnerScroll = e => {
  // 可以在这里处理水平滚动的逻辑
};

// 处理添加按钮点击
const handleAdd = () => {
  // 打开区域选择器
  showAreaPicker.value = true;
};

// 设置状态栏样式
const setStatusBarStyle = () => {
  // #ifdef APP-PLUS
  plus.navigator.setStatusBarStyle('light');
  // #endif
};

onMounted(async () => {
  setStatusBarStyle();

  // 获取筛选区域数据
  await fetchFilterAreaData();

  // 获取区域选择器数据
  await fetchAreaPickerData();

  // 等待筛选组件初始化完成后，触发初始数据加载
  nextTick(async () => {
    // 等待筛选组件完全初始化
    await new Promise(resolve => setTimeout(resolve, 100));

    // 新的筛选组件会自动选择第一个选项，我们只需要触发一次数据加载
    if (filterAreaData.value.length > 0) {
      // 模拟一级筛选变化，触发数据加载
      await handleFilterChange({
        type: 'filter1',
        filter1: filterAreaData.value[0],
      });
    }
  });
});
</script>

<style scoped lang="scss">
.public-page {
  @include page-with-header;
  min-height: 100vh;
  background: #172869;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  padding: 40rpx 32rpx;
  box-sizing: border-box;
}

/* 标题和图例区域 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.page-title {
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
}

.legend-section {
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.legend-text {
  color: #fff;
  font-size: 24rpx;
}

.legend-dot {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;

  &.normal {
    background: #1ec8e1;
  }

  &.abnormal {
    background: #ff4757;
  }
}

/* 表格区域 */
.table-section {
  background: rgba(255, 255, 255, 0.08);
  border-radius: 4rpx;
}

.table-header {
  display: flex;
  background: rgba(255, 255, 255, 0.1);
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
  padding: 24rpx 40rpx 0;
}

.table-body {
  padding: 0 26rpx 0 20rpx;
  box-sizing: border-box;
  position: relative;
  z-index: 1;
}

.table-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-content {
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.row-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #1a3a6a;
  min-height: 60rpx;

  &:last-child {
    border-bottom: none;
  }
}

.label-container {
  flex-shrink: 0;
  width: 120rpx;
  padding-right: 10rpx;
  overflow: hidden;
}

.label-scroll {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}

.label-text {
  font-size: 24rpx;
  color: #fff;
  white-space: nowrap;
  flex-shrink: 0;
}

.scroll-container {
  flex: 1;
  overflow: hidden;
  width: 100%;
}

.horizontal-scroll {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-evenly;
}

.horizontal-scroll-inner {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}

.data-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-evenly;
  margin-right: 16rpx;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  min-width: 80rpx;
  max-width: 120rpx;
  text-align: center;

  &.normal {
    background: rgba(30, 200, 225, 0.1); // 半透明蓝色
  }

  &.abnormal {
    background: rgba(255, 71, 87, 0.1); // 半透明红色
  }
}

.data-text {
  flex: 1;
  font-size: 20rpx;
  color: #fff;
  font-weight: 500;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.custom-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  left: 0;
  right: 0;
  bottom: -60rpx;
  z-index: 2;
  height: 6rpx;
  gap: 8rpx;
  background: transparent;
}

.indicator-dot {
  height: 6rpx;
  border-radius: 5rpx;
  background: #4a5a8a;
  width: 40rpx;
  transition: all 0.3s;
  opacity: 0.5;
  margin-right: 12rpx;

  &:last-child {
    margin-right: 0;
  }

  &.active {
    width: 80rpx;
    background: #fff;
    opacity: 1;
    box-shadow: 0 2rpx 8rpx rgba(255, 255, 255, 0.12);
    border-radius: 5rpx;
  }
}

.bottom-actions {
  width: 100%;
  height: 168rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 30rpx;
  box-sizing: border-box;
}

.add-btn {
  width: 686rpx;
  height: 80rpx;
  background: linear-gradient(90deg, #3a8dde 0%, #256bda 100%);
  color: #fff;
  font-size: 32rpx;
  border: none;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(58, 108, 255, 0.12);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;

  &:active {
    transform: scale(0.98);
  }
}

/* Picker组件样式 */
:deep(.uni-picker-view-mask) {
  background: transparent !important;
}

:deep(.tn-picker__content) {
  background: #172869 !important;
  border-radius: 20rpx 20rpx 0 0 !important;
}

:deep(.tn-picker__header) {
  background: #172869 !important;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1) !important;
}

:deep(.tn-picker__confirm) {
  color: #1ec8e1 !important;
}

:deep(.tn-picker__cancel) {
  color: rgba(255, 255, 255, 0.6) !important;
}

:deep(.tn-picker__title) {
  color: #fff !important;
}

:deep(.tn-picker-view__item) {
  color: #fff !important;
}

:deep(.tn-picker-view__item--selected) {
  color: #1ec8e1 !important;
}
</style>
